<template>
	<view>
		<view class="box">
			<canvas canvas-id="writeText" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"
				style="width: 400px;height: 300px;"></canvas>
			<view class="btn-box">
				<view class="clear-btn btn" @click="clearDraw">清除标签</view>
				<view class="save-btn btn" @click="saveDraw">保存标签</view>
			</view>
		</view>
	</view>
</template>

<script>
	let ctx = null;
	export default {
		data() {
			return {
				isDrawing: false,
				siteX: 0,
				siteY: 0
			};
		},
		methods: {
			startDrawing(e) {
				this.isDrawing = true;
				this.siteX = e.pageX - e.target.offsetLeft;
				this.siteY = e.pageY - e.target.offsetTop;
			},
			draw(e) {
				if (!this.isDrawing) return;
				let lastX = e.pageX - e.target.offsetLeft;
				let lastY = e.pageY - e.target.offsetTop;
				ctx.beginPath();
				ctx.moveTo(this.siteX, this.siteY);
				ctx.lineTo(lastX, lastY);
				ctx.stroke();
				ctx.draw(true);
				this.siteX = lastX;
				this.siteY = lastY;
			},
			stopDrawing() {
				this.isDrawing = false;
			},
			clearDraw() {
				ctx.clearRect(0, 0, 400, 300)
				ctx.draw()
			},
			saveDraw() {
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: 400,
					height: 300,
					canvasId: 'writeText',
					success: function(res) {
						let image = res.tempFilePath;
						let link = document.createElement("a");
						link.download = "signature.png";
						link.href = image;
						link.click();
					}
				})
			}
		},
		onLoad() {
			ctx = uni.createCanvasContext('writeText');
		}
	}
</script>

<style lang="scss">
	canvas {
		border: 2rpx solid orangered;
	}

	.box {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100vh;
	}

	.btn-box {
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 150rpx;
		height: 50rpx;
		margin-top: 40rpx;
		background: linear-gradient(to right, orangered, mediumpurple);
		color: white;
		font-size: 24rpx;
		font-weight: 500;
	}

	.clear-btn {
		margin-right: 36rpx;
	}
</style>